/**
 *
 */
package com.evangelion.core.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.evangelion.core.bean.Alumno;
import com.evangelion.core.bean.Examen;
import com.evangelion.core.bean.Profesor;
import com.evangelion.core.bean.Vehiculo;
import com.evangelion.core.daoImpl.ConnectionUtil;
import com.evangelion.core.pojo.ExamenPracticoSearchForm;
import com.evangelion.core.utils.MensajesFace;
import com.evangelion.web.filter.SecurityUtils;

/**
 * @author Rick Chen
 */
@ManagedBean
@ViewScoped
public class DgtPracticoController extends MensajesFace implements Serializable {

    private Examen examen;

    private List<Examen> examenList;

    private LazyDataModel<Alumno> listAlumno;

    private String searchParamAlumno2;

    private List<Examen> examenList2;

    private DefaultStreamedContent dc;

    private Examen practicoExam;
    private String practicoExamProfesor = "";

    private ExamenPracticoSearchForm practicoSearchForm;
    private LazyDataModel<Profesor> practicoProfesorList;

    private List<Vehiculo> vehiculoList;

    @PostConstruct
    @Override
    public void init() {
        super.init();

        practicoExam = new Examen();
        practicoExam.setProfesor(new Profesor());
        practicoExam.setVehiculo(new Vehiculo());
        practicoExamProfesor = "";
        searchParamAlumno2 = "";
        searchExamProfesor();
        practicoSearchForm = new ExamenPracticoSearchForm();

        examen = new Examen();
        examenList = new ArrayList<Examen>();
    }

    public void searchPratico() {
        List<String> pruebaList = new ArrayList<String>();

        pruebaList.add("Mecanico");
        pruebaList.add("Especifico");
        pruebaList.add("Circuito abierto");
        pruebaList.add("Circuito cerrado");
        if (StringUtils.isEmpty(practicoSearchForm.getProfessorStr())) {
            practicoSearchForm.setProfessor(null);
        }
        examenList2 = examenService.findByRangeDate(practicoSearchForm.getProfessor(), seccion, practicoSearchForm.getFechaDesde(), practicoSearchForm.getFechaHasta(), pruebaList);

    }

    public void printPratico() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        List pruebaList = new ArrayList();
        pruebaList.add("Mecanico");
        pruebaList.add("Especifico");
        pruebaList.add("Circuito abierto");
        pruebaList.add("Circuito cerrado");

        practicoSearchForm.setSeccion(seccion);

        Map parameters = new HashMap();
        parameters.put("rpt_prueba_list", pruebaList);
        parameters.put("rpt_seccion_id", "" + SecurityUtils.getSeccion(request).getId());

        Calendar calendar = Calendar.getInstance();
        if (null == practicoSearchForm.getFechaDesde()) {
            calendar.add(Calendar.YEAR, -1);
            parameters.put("rpt_desde", calendar.getTime());
        } else {
            parameters.put("rpt_desde", practicoSearchForm.getFechaDesde());
        }

        if (null == practicoSearchForm.getFechaHasta()) {
            calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            parameters.put("rpt_hasta", calendar.getTime());
        } else {
            parameters.put("rpt_hasta", practicoSearchForm.getFechaHasta());
        }

        List<Profesor> profesors = examenService.findProfessor(practicoSearchForm, pruebaList);

        printPraticoReport(profesors, parameters, "ExamenPracticoReport");
    }

    public void printPraticoReport(List<Profesor> profesors, Map parameters, String reportName) {
        try {

            String urlMaster = ConnectionUtil.getServletContext().getRealPath(REPORT_FOLDER + reportName + ".jasper");
            JasperReport reporteMaster = null;
            try {
                reporteMaster = (JasperReport) JRLoader.loadObject(urlMaster);
            } catch (Exception e) {
                e.printStackTrace();
            }

            List<JasperPrint> reportsList = new ArrayList<JasperPrint>();
            Connection conexion = connectionUtil.getConnection();
            for (Profesor profesor : profesors) {
                parameters.put("rpt_profesor_id", "" + profesor.getId());
                parameters.put("rpt_profesor_nif", profesor.getNif());
                parameters.put("rpt_profesor_name", profesor.getNombres());

                JasperPrint print = JasperFillManager.fillReport(reporteMaster, parameters, conexion);
                reportsList.add(print);
            }

            byte[] bytes = JasperExportManager.exportReportToPdf(mergeReport(reportsList));

//            if (bytes.length >= 1211 && bytes.length <= 1400) {
//                dc = null;
//            } else {
            Calendar calendar = Calendar.getInstance();

            InputStream stream = new ByteArrayInputStream(bytes);
            dc = new DefaultStreamedContent(stream, "application/pdf", "/general/teorico_" + calendar.getTimeInMillis() + ".pdf");
//            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void savePractico() {
        boolean valid = true;
        if (null == practicoExam.getProfesor() || null == practicoExam.getProfesor().getId()) {
            msgAdvertencia("El campo \"Profesor\" es requerido");
            valid = false;
        }

        if (null == practicoExam.getVehiculo() || null == practicoExam.getVehiculo().getId()) {
            msgAdvertencia("El campo \"Vehiculo\" es requerido");
            valid = false;
        }

        if (!valid) {
            return;
        }

        practicoExam.setEstadoexamen("Activo");

        practicoExam.setCliente(usuario.getCliente());
        practicoExam.setSeccion(seccion);
        examenService.save(practicoExam);

        init();
        msgCambiosGuardados();
    }

    public void onRowSelectAlumno(Alumno alumno) {
        practicoExam.setAlumno(alumno);
        searchParamAlumno2 = alumno.getNombres() + " " + alumno.getApellidos();
    }

    public void searchPracticoAlumno() {
        configDataModelFacAlum(searchParamAlumno2);
    }

    @SuppressWarnings("serial")
    public void configDataModelFacAlum(final String valor) {
        listAlumno = new LazyDataModel<Alumno>() {
            @Override
            public List<Alumno> load(int start, int max, String arg2, SortOrder arg3, Map<String, String> arg4) {

                return serviceAlunmo.searchByNifNombre(seccion, valor, start, max);

            }
        };
        listAlumno.setRowCount(serviceAlunmo.countPage(seccion, valor));
    }

    public void onRowSelectVehiculo(Vehiculo vehicul) {
        practicoExam.setVehiculo(vehicul);

    }

    public void searchProfesor() {
        practicoProfesorList = searchProfessor(this.getPracticoSearchForm().getProfessorStr(), seccion);
    }

    public void searchExamProfesor() {
        practicoProfesorList = searchProfessor(this.practicoExamProfesor, seccion);
    }

    public void searchVehiculo() {
        vehiculoList = vehiculoService.findListByParamSeccion(seccion, "matricula", practicoExam.getVehiculo().getMatricula());
    }

    public void onRowSelectExamProfesor(Profesor professor) {
        this.practicoExam.setProfesor(professor);
        this.practicoExamProfesor = professor.getNombres();
    }

    public void onRowSelectSearchProfesor(Profesor professor) {
        this.practicoSearchForm.setProfessor(professor);
        this.practicoSearchForm.setProfessorStr(professor.getNombres());
        practicoSearchForm.setProfessorStr(professor.getNombres() + " " + professor.getApellidos());
    }

    public Examen getExamen() {
        return examen;
    }

    public void setExamen(Examen examen) {
        this.examen = examen;
    }

    public List<Vehiculo> getVehiculoList() {
        return vehiculoList;
    }

    public void setVehiculoList(List<Vehiculo> vehiculoList) {
        this.vehiculoList = vehiculoList;
    }

    public List<Examen> getExamenList() {
        return examenList;
    }

    public void setExamenList(List<Examen> examenList) {
        this.examenList = examenList;
    }

    public LazyDataModel<Alumno> getListAlumno() {
        return listAlumno;
    }

    public void setListAlumno(LazyDataModel<Alumno> listAlumno) {
        this.listAlumno = listAlumno;
    }

    public List<Examen> getExamenList2() {
        return examenList2;
    }

    public void setExamenList2(List<Examen> examenList2) {
        this.examenList2 = examenList2;
    }

    public String getSearchParamAlumno2() {
        return searchParamAlumno2;
    }

    public void setSearchParamAlumno2(String searchParamAlumno2) {
        this.searchParamAlumno2 = searchParamAlumno2;
    }

    /**
     * @return the dc
     */
    public DefaultStreamedContent getDc() {
        return dc;
    }

    /**
     * @param dc the dc to set
     */
    public void setDc(DefaultStreamedContent dc) {
        this.dc = dc;
    }

    public Examen getPracticoExam() {
        return practicoExam;
    }

    public void setPracticoExam(Examen practicoExam) {
        this.practicoExam = practicoExam;
    }

    public ExamenPracticoSearchForm getPracticoSearchForm() {
        return practicoSearchForm;
    }

    public void setPracticoSearchForm(ExamenPracticoSearchForm practicoSearchForm) {
        this.practicoSearchForm = practicoSearchForm;
    }

    public LazyDataModel<Profesor> getPracticoProfesorList() {
        return practicoProfesorList;
    }

    public void setPracticoProfesorList(LazyDataModel<Profesor> practicoProfesorList) {
        this.practicoProfesorList = practicoProfesorList;
    }

    public String getPracticoExamProfesor() {
        return practicoExamProfesor;
    }

    public void setPracticoExamProfesor(String practicoExamProfesor) {
        this.practicoExamProfesor = practicoExamProfesor;
    }
}
